package com.example.mykotilin.workmanager

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.provider.MediaStore
import android.text.Html
import android.text.Html.fromHtml
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.VisibleForTesting
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.mykotilin.R
import com.example.mykotilin.databinding.ActivitySelectBinding
import com.example.mykotilin.workmanager.lib.Constants
import com.google.android.material.snackbar.Snackbar
import java.util.ArrayList

/**
 *
 *
 *
 */
class SelectImageActivity : AppCompatActivity() {
    private var permissionRequestCount = 0;
    private var hasPermissions = false;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivitySelectBinding.inflate(layoutInflater).apply {
            setContentView(root)
        }
        with(binding) {
            credits.text = fromHtml(getString(R.string.credits))
            credits.movementMethod = LinkMovementMethod.getInstance()
        }

        if (savedInstanceState != null) {
            permissionRequestCount = savedInstanceState.getInt(KEY_PERMISSIONS_REQUEST_COUNT, 0)
        }

        requestPermissionsIfNecessary()  //请求是否需要权限
        with(binding) {
            selectImage.setOnClickListener {
                val chooseIntent = Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                )
                startActivityForResult(chooseIntent, REQUEST_CODE_IMAGE)
            }

            selectStockImage.setOnClickListener {
                startActivity(
                    FilterActivity.newIntent(
                        this@SelectImageActivity,
                        StockImages.randomStockImage()
                    )
                )
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        outState.putInt(KEY_PERMISSIONS_REQUEST_COUNT, permissionRequestCount)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                REQUEST_CODE_IMAGE -> handleImageRequestResult(data)
                else -> Log.d(TAG, "Unknown request code")
            }
        } else {
            Log.e(TAG, String.format("Unexpected Result code \"%s\" or missing data.", resultCode))
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            requestPermissionsIfNecessary()
        }
    }


    private fun handleImageRequestResult(data: Intent) {
        val imageUri = data.clipData!!.getItemAt(0).uri
        if (imageUri == null) {
            Log.e(TAG, "Invalid input image Uri.")
            return
        }
        startActivity(FilterActivity.newIntent(this, imageUri))
    }

    @SuppressLint("ShowToast")
    private fun requestPermissionsIfNecessary() { //申请权限
        hasPermissions = checkAllPermissions() //检查权限
        if (!hasPermissions) {
            if (permissionRequestCount < MAX_NUMBER_REQUEST_PERMISSIONS) { //判断请求的次数
                permissionRequestCount += 1 //每次调用让请求次数+1.
                ActivityCompat.requestPermissions(
                    this,
                    sPermissions.toTypedArray(),
                    REQUEST_CODE_PERMISSIONS
                )
            } else { //如果2次都拒绝请求，弹出提示
                Snackbar.make(
                    findViewById(R.id.coordinatorLayout),
                    R.string.set_permissions_in_settings,
                    Snackbar.LENGTH_INDEFINITE
                )
                findViewById<View>(R.id.selectImage).isEnabled = false
            }
        }
    }

    private fun checkAllPermissions(): Boolean {
        var hasPermissions = true
        for (permission in sPermissions) {
            hasPermissions = hasPermissions and (ContextCompat.checkSelfPermission(
                this, permission
            ) == PackageManager.PERMISSION_GRANTED)
        }
        return hasPermissions
    }

    companion object {
        private const val TAG = "SelectImageActivity"
        //权限请求次数键
        private const val KEY_PERMISSIONS_REQUEST_COUNT = "KEY_PERMISSIONS_REQUEST_COUNT"
        //权限请求最大数
        private const val MAX_NUMBER_REQUEST_PERMISSIONS = 2

        private const val REQUEST_CODE_IMAGE = 100
        //权限请求码
        private const val REQUEST_CODE_PERMISSIONS = 101

        @VisibleForTesting
        val sPermissions: MutableList<String> = object : ArrayList<String>() {
            init {
                add(Manifest.permission.INTERNET)
                add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }

        private fun fromHtml(input: String): Spanned {
            return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                Html.fromHtml(input, Html.FROM_HTML_MODE_COMPACT)
            } else {
                @Suppress("DEPRECATION")
                Html.fromHtml(input)
            }
        }
    }
}